import json
import os
from concurrent.futures import ThreadPoolExecutor
from typing import Optional, Any

import aiofiles
from celery.result import AsyncResult
from fastapi import APIRouter, Depends, BackgroundTasks
from fastapi_async_sqlalchemy import db
from flask import Request
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.asyncio import AsyncSession
from starlette.concurrency import run_in_threadpool

from starlette.responses import FileResponse
from sqlalchemy.future import select
from sqlalchemy import delete
from common.fu_async_crud import create, update, retrieve, query_filter, batch_create
from common.fu_schema import IdSchema
from common.utils.list_to_tree import list_to_tree
from .model import UiCase, UiCaseStep
from .schema import UiCaseFilters, UiCaseOut, UiCaseIn, UiCaseStepIn, CaseOut, CaseIn, StepOut
from config import STATIC_URL, BASE_DIR,DEBUG_VIDEO_URL,DEBUG_FILE_URL
from .task import execute_ui_task, task_status, do_execute_ui_task

import uuid

router = APIRouter(tags=["Case"])

executor = ThreadPoolExecutor(4)



@router.get('/video')
async def get_video(filename):
    file_path = os.path.join(BASE_DIR, STATIC_URL,DEBUG_VIDEO_URL,filename+".webm")
    # 确保文件存在
    print(file_path)
    if not os.path.exists(file_path):
        return {"status":200,"data":"没有该文件"}

    # 打开文件并返回
        # 使用 Response 返回文件流
    return FileResponse(file_path, media_type="video/webm")

@router.get('/case/debug/log/{case_id}')
async def get_case_debug_log(request:Request,case_id:str):
    file_path = os.path.join(BASE_DIR, STATIC_URL, DEBUG_FILE_URL, case_id + '.txt')
    if not os.path.exists(file_path):
        return {"status": "success", "data": ["没有运行日志","1.输入执行步骤","2.输入断言","3.运行执行"],"task_status":0}

    async with aiofiles.open(file_path, 'r', encoding='utf-8') as f:
        lines = []
        async for line in f:
            lines.append(line.strip())  # 去除每行的换行符
        if not lines:
            return {"status": "success", "data": ["没有运行日志","1.输入执行步骤","2.输入断言","3.运行执行"],"task_status":0}
        async_result = AsyncResult(case_id)
        if async_result.state == "STARTED":
            return {"status": "success", "task_status":1,"data": lines}
        else:
            return {"status": "success", "task_status":0,"data": lines}


@router.post('/case/debug/{case_id}')
async def start_task_endpoint(request:Request,case_id: str,uiCaseStepIn:list[UiCaseStepIn]):
    try:
        print(uiCaseStepIn)
        file_path = os.path.join(BASE_DIR,STATIC_URL,DEBUG_FILE_URL,case_id+'.txt')
        async_result = AsyncResult(case_id)
        if async_result.state == "STARTED":
            return {"status": "success", "message": "任务正在执行"}
        async with aiofiles.open(file_path, 'w', encoding='utf-8') as file:
            await file.write("用例开始运行！！！！！！！！！！！！")  # 只创建文件，不写入任何内容
        uiCaseStepInJson = [item.model_dump() for item in uiCaseStepIn]

        task = do_execute_ui_task.apply_async(args=[case_id, uiCaseStepInJson, file_path],task_id=case_id)


        return {"status": "success", "message": "任务开始执行"}
    except Exception as e:
        return {"status": "error", "message": str(e)}

@router.post("/case", response_model=IdSchema)
async def create_case(data: UiCaseIn):
    instance = await create(data, UiCase)
    return instance

@router.delete("/case/{case_id}", response_model=IdSchema)
async def delete_case(case_id: str):
    instance = await delete(case_id, UiCase)
    return instance

@router.put("/case/{case_id}", response_model=IdSchema)
async def update_case(case_id: str, data: UiCaseIn):
    instance = await update(case_id, data, UiCase)
    return instance

@router.get("/case/list", response_model=list[UiCaseOut])
async def list_case(params: UiCaseFilters = Depends()):
    instance_list = await retrieve(UiCase, UiCaseOut, is_pagination=False, filters=params)
    return instance_list

@router.get("/case/tree", response_model=list[UiCaseOut])
async def case_tree(params: UiCaseFilters = Depends()):
    # 使用 joinedload 预加载父子关系，减少查询次数
    instance_list = await retrieve(
        UiCase,
        UiCaseOut,
        is_pagination=False,
        filters=params
    )
    dept_list = [item.dict() for item in instance_list]
    # 将查询集转换成树形结构
    dept_tree = list_to_tree(dept_list)
    return dept_tree


# **查询步骤接口**
@router.get("/case/steps/{case_id}", response_model=CaseOut)
async def get_case_steps(case_id: str):

    session = db.session
    query = select(UiCaseStep)
    filters = {
        "case_id__eq": case_id,  # case_id 等于某个值
         # sys_flag 不等于 0

    }
    # 使用 query_filter 函数来应用过滤
    filtered_query = query_filter(filters, query, UiCaseStep)    # 执行查询
    result = await session.execute(filtered_query)
    steps = result.scalars().all()
    print(steps)
    step_out_list = [
        StepOut(
            id=step.id,
            step_description=step.step_description,
            assertion=step.assertion,
            order=step.order,
            assert_type=step.assert_type,
            case_id=step.case_id,
        )
        for step in steps
    ]

    # 返回 CaseOut 对象
    return CaseOut(case_id=case_id, steps=step_out_list)

# **添加步骤接口**
@router.post("/case/steps/{case_id}")
async def add_case_steps(case_id: str, case_in: CaseIn):
    # **1. 先删除旧的步骤**
    session: AsyncSession = db.session
    try:
        result = await session.execute(delete(UiCaseStep).where(UiCaseStep.case_id == case_id))
        print(f"Deleted rows: {result.rowcount}")  # 打印删除的行数
    except SQLAlchemyError as e:
        # 捕获删除步骤时的异常并打印详细信息
        print("Error deleting old steps:", e)
        return {"status": 200, "data": "Failed to delete old steps", "error": str(e)}


    # **2. 插入新的步骤**
    new_steps = [
        UiCaseStep(
            id=uuid.uuid4(),
            step_description=step.step_description,
            assertion=step.assertion,
            order=step.order,
            assert_type=step.assert_type,
            case_id=uuid.UUID(case_id),
        )
        for step in case_in.steps
    ]

    session.add_all(new_steps)
    # try:
    await session.commit()




    return {'status':200,'data':'保存成功'}